<template>
    <div class="container" ref="container"></div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import earthImg from "./images/earth.jpg";

// 渲染器
let renderer: THREE.WebGLRenderer;
// 场景
let scene: THREE.Scene;
// 地球模型
let earthMesh: THREE.Mesh;
// 相机
let camera: THREE.OrthographicCamera;
// 容器
let container = ref<HTMLElement>();

onMounted(init);

async function init() {
    // 屏幕宽高
    let w = container.value.clientWidth;
    let h = container.value.clientHeight;
    // 渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(w, h);
    container.value.appendChild(renderer.domElement);
    // 场景
    scene = new THREE.Scene();
    // 加载纹理图
    let texture = await new Promise<THREE.Texture>((resolve) => {
        new THREE.TextureLoader().load(earthImg, (texture) => {
            resolve(texture);
        });
    });
    // 材质和形状
    let material = new THREE.MeshBasicMaterial({ map: texture });
    let geometry = new THREE.SphereGeometry(100, 500, 500);
    // 创建地球模型
    earthMesh = new THREE.Mesh(geometry, material);

    earthMesh.rotation.y = Math.PI;
    scene.add(earthMesh);

    // 相机
    camera = new THREE.OrthographicCamera(-(110 * w) / h, (110 * w) / h, 110, -110);
    camera.position.set(0, 0, 200);
    camera.lookAt(0, 0, 0);

    // 渲染界面
    renderer.render(scene, camera);

    var controls = new OrbitControls(camera, renderer.domElement);
    controls.addEventListener("change", () => {
        renderer.render(scene, camera);
    });
}
</script>
<style scoped lang="scss">
.container {
    height: 100%;
}
</style>
